package org.example.mall.controller;

import jakarta.servlet.http.HttpSession;
import org.example.mall.entity.User;
import org.example.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/user")
public class UserViewController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public String register(@RequestParam String username,
                         @RequestParam String password,
                         @RequestParam String email,
                         @RequestParam(required = false) MultipartFile avatar,
                         RedirectAttributes redirectAttributes) {
        try {
            User user = userService.register(username, password, email, avatar);
            redirectAttributes.addFlashAttribute("message", "注册成功！请登录");
            return "redirect:/login";
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/register";
        } catch (Exception e) {
            log.error("注册失败", e);
            redirectAttributes.addFlashAttribute("error", "注册失败，请稍后重试");
            return "redirect:/register";
        }
    }

    @PostMapping("/register/phone")
    public String registerByPhone(@RequestParam String phone,
                                @RequestParam String verificationCode,
                                @RequestParam String password,
                                @RequestParam String email,
                                @RequestParam(required = false) MultipartFile avatar,
                                RedirectAttributes redirectAttributes) {
        try {
            User user = userService.registerByPhone(phone, verificationCode, password, email, avatar);
            redirectAttributes.addFlashAttribute("message", "注册成功！请登录");
            return "redirect:/login";
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/register";
        } catch (Exception e) {
            log.error("手机号注册失败", e);
            redirectAttributes.addFlashAttribute("error", "注册失败，请稍后重试");
            return "redirect:/register";
        }
    }

    @PostMapping("/login")
    public String login(@RequestParam String username,
                       @RequestParam String password,
                       HttpSession session,
                       RedirectAttributes redirectAttributes) {
        try {
            User user = userService.login(username, password);
            session.setAttribute("user", user);
            
            // 添加日志，输出用户信息和头像路径
            log.info("用户登录成功: {}, 头像路径: {}", user.getUsername(), user.getAvatar());
            
            redirectAttributes.addFlashAttribute("message", "登录成功！");
            return "redirect:/mall";
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/login";
        } catch (Exception e) {
            log.error("登录失败", e);
            redirectAttributes.addFlashAttribute("error", "登录失败，请稍后重试");
            return "redirect:/login";
        }
    }

    @PostMapping("/login/phone")
    public String loginByPhone(@RequestParam String phone,
                             @RequestParam(required = false) String verificationCode,
                             @RequestParam(required = false) String password,
                             @RequestParam(required = false) String loginType,
                             HttpSession session,
                             RedirectAttributes redirectAttributes) {
        try {
            User user;
            if ("password".equals(loginType)) {
                user = userService.loginByPhonePassword(phone, password);
            } else {
                user = userService.loginByPhone(phone, verificationCode);
            }
            
            session.setAttribute("user", user);
            redirectAttributes.addFlashAttribute("message", "登录成功！");
            return "redirect:/mall";
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/login";
        } catch (Exception e) {
            log.error("手机号登录失败", e);
            redirectAttributes.addFlashAttribute("error", "登录失败，请稍后重试");
            return "redirect:/login";
        }
    }
    
    @GetMapping("/profile")
    public String profile(HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录");
            return "redirect:/login";
        }
        return "profile";
    }
    
    @GetMapping("/change-password")
    public String changePassword(HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录");
            return "redirect:/login";
        }
        return "change-password";
    }
    
    @PostMapping("/update-profile")
    public String updateProfile(@RequestParam(required = false) String nickname,
                                @RequestParam String email,
                                @RequestParam(required = false) MultipartFile avatar,
                                HttpSession session,
                                RedirectAttributes redirectAttributes) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录");
            return "redirect:/login";
        }
        
        try {
            User userInfo = new User();
            userInfo.setNickname(nickname);
            userInfo.setEmail(email);
            
            // 处理头像上传
            if (avatar != null && !avatar.isEmpty()) {
                // 头像处理逻辑由userService实现
            }
            
            User updatedUser = userService.updateUserInfo(currentUser.getId(), userInfo, avatar);
            session.setAttribute("user", updatedUser);  // 更新session中的用户信息
            
            redirectAttributes.addFlashAttribute("message", "个人信息更新成功");
            return "redirect:/user/profile";
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/user/profile";
        } catch (Exception e) {
            log.error("更新个人信息失败", e);
            redirectAttributes.addFlashAttribute("error", "更新个人信息失败，请稍后重试");
            return "redirect:/user/profile";
        }
    }
    
    @PostMapping("/update-password")
    public String updatePassword(@RequestParam String oldPassword,
                                @RequestParam String newPassword,
                                @RequestParam String confirmPassword,
                                HttpSession session,
                                RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录");
            return "redirect:/login";
        }
        
        // 验证两次输入的新密码是否一致
        if (!newPassword.equals(confirmPassword)) {
            redirectAttributes.addFlashAttribute("error", "两次输入的新密码不一致");
            return "redirect:/user/change-password";
        }
        
        try {
            boolean success = userService.updatePassword(user.getId(), oldPassword, newPassword);
            if (success) {
                redirectAttributes.addFlashAttribute("message", "密码修改成功，请重新登录");
                session.invalidate();  // 清除session，强制用户重新登录
                return "redirect:/login";
            } else {
                redirectAttributes.addFlashAttribute("error", "密码修改失败，请检查原密码是否正确");
                return "redirect:/user/change-password";
            }
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/user/change-password";
        } catch (Exception e) {
            log.error("修改密码失败", e);
            redirectAttributes.addFlashAttribute("error", "修改密码失败，请稍后重试");
            return "redirect:/user/change-password";
        }
    }
    
    @GetMapping("/logout")
    public String logout(HttpSession session, RedirectAttributes redirectAttributes) {
        session.invalidate();
        redirectAttributes.addFlashAttribute("message", "您已成功退出登录");
        return "redirect:/login";
    }

    @GetMapping("/check-phone")
    @ResponseBody
    public boolean checkPhone(@RequestParam String phone) {
        return userService.isPhoneRegistered(phone);
    }
}